
from pluginHelper import *
import re

ro = re.compile("^\s*for\s+", re.M)
#ro = re.compile("^\s*(for|while)", re.M)

SEVERITY = 5

#
# This is a scanner function that can scan the file line-by-line.
# The function is called once for each line in the input file. THe filename
# and current line number is passed to the function. The function returns
# a boolean value indicating whether it wants more input (True), or whether
# it does not care any moer about this file (False).
#
# errors are reported using reportError(line, col)
#
def scanFile(self, file):
	data = file.read()
	so = ro.search(data)
	while so:
		start = so.start()
		end = so.end()
		# find the end of the loop:
		bc = 0;
		openFound = False
		i = start
		while 1:
			if data[i] == '(':
				bc += 1
				openFound = True
			elif data[i] == ')':
				bc -= 1

			if openFound and bc == 0:
				end = i
				break
			i += 1
		#
		# we found the end of the for loop - now look for a semi-colon:
		while 1:
			i += 1
			if data[i] == ';':
				# report error:
				lineStart = len(data[:start].split('\n'))
				lineEnd = len(data[:end].split('\n'))
				reportError(lineStart,0,SEVERITY)
				break
			if not data[i].isspace():
				break
		so = ro.search(data, end)
	#
	# Assume that each loop starts on a new line:
	return True


#
# Describe the plugin:
if __name__ == "__main__":
	init()
	describePlugin('loopsemi','scanner', 'Checks for semicolons (;) at the end of "for" loop statements.')

#	addOption('checkWhile','Check "While" loops', True);
#	addOption('checkFor','Check "For" loops', True);

	#
	# Set the scan function, along with it's type:
	setScanFunction(SCANNER_TYPE_FILE_OBJECT, scanFile)


